package course.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import course.pojo.entity.College;
import course.pojo.entity.Teacher;
import course.pojo.vo.Page;
import course.pojo.vo.TeacherRespVo;
import course.service.CollegeService;
import course.service.TeacherService;
import course.service.impl.CollegeServiceImpl;
import course.service.impl.TeacherServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author HLF
 * @date 2022/7/2 9:17
 */
@WebServlet("/admin/teacherController")
public class TeacherController extends BaseController {
    private TeacherService teacherService = new TeacherServiceImpl();

    private CollegeService collegeService = new CollegeServiceImpl();

    /**
     * @Version 3.0
     */
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        CollegeService collegeService = new CollegeServiceImpl();
        List<College> list = collegeService.getList();
        req.setAttribute("list", list);

        req.getRequestDispatcher("/teacher_add.jsp").forward(req, resp);
    }

    protected void updatePage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        CollegeService collegeService = new CollegeServiceImpl();
        List<College> list = collegeService.getList();
        req.setAttribute("list", list);

        req.getRequestDispatcher("/teacher_update.jsp").forward(req, resp);
    }

    protected void index(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pageNo = req.getParameter("pageNo");
        this.main(req, resp, pageNo);
    }

    /**
     * 传递分页参数进行分页
     */
    protected void main(HttpServletRequest req, HttpServletResponse resp, String pageNo) throws ServletException, IOException {
        if (pageNo == null || Integer.parseInt(pageNo) <= 0) {
            pageNo = "1";
        }

        Page<Teacher> page = teacherService.page(Integer.valueOf(pageNo));
        List<Teacher> teacherList = page.getList();
        List<TeacherRespVo> respVos = teacherList.stream().map(teacher -> {
            try {
                TeacherRespVo respVo = new TeacherRespVo();
                BeanUtils.copyProperties(respVo, teacher);
                String cname = collegeService.getById(teacher.getCid()).getCname();
                respVo.setCname(cname);

                return respVo;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());

        Page<TeacherRespVo> voPage = new Page<>();
        try {
            BeanUtils.copyProperties(voPage, page);
            voPage.setList(respVos);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        req.setAttribute("page", voPage);
        req.getRequestDispatcher("/teacher_manage.jsp").forward(req, resp);
    }

    /**
     * 添加教师
     */
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String tname = req.getParameter("tname");
        String tsex = req.getParameter("tsex");
        String tphone = req.getParameter("tphone");
        String temail = req.getParameter("temail");
        String cid = req.getParameter("cid");

        String total = req.getParameter("total");//获取总数量
        String pages = req.getParameter("pages");//获取总页码数

        Integer pageSize = new Page<>().getPageSize();

        Integer pages2 = Integer.valueOf(pages);
        if (Integer.parseInt(total) % pageSize == 0) {
            pages2 += 1;
        }

        Teacher teacher = new Teacher(null, tname, tsex, tphone, temail, Integer.valueOf(cid));
        int i = teacherService.addTeacher(teacher);
        if (i > 0) {
            this.main(req, resp, String.valueOf(pages2));
        }
    }

    /**
     * 删除教师
     */
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String tid = req.getParameter("tid");
        String pn = req.getParameter("pn");

        int i = teacherService.deleteById(Integer.valueOf(tid));
        if (i > 0) {
            this.main(req, resp, pn);
        }
    }

    /**
     * 批量删除所有选中教师
     */
    protected void deleteSelect(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] ids = req.getParameterValues("ids[]");

        List<String> list = Arrays.asList(ids);
        List<Integer> integers = list.stream().map(Integer::valueOf).collect(Collectors.toList());

        int i = teacherService.deleteSelect(integers);
        if (i > 0) {
            this.index(req, resp);
        }
    }

    /**
     * 通过tid获取teacher对象
     */
    protected void getTeacher(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        String tid = req.getParameter("tid");

        Teacher teacher = teacherService.getById(Integer.valueOf(tid));
        ObjectMapper mapper = new ObjectMapper();

        College college = collegeService.getById(teacher.getCid());
        TeacherRespVo teacherRespVo = new TeacherRespVo();
        try {
            BeanUtils.copyProperties(teacherRespVo, teacher);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        teacherRespVo.setCname(college.getCname());

        String jsonString = mapper.writeValueAsString(teacherRespVo);
        PrintWriter writer = resp.getWriter();
        writer.write(jsonString); //将json对象响应给前端
        writer.flush();
    }

    /**
     * 修改教师
     */
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String tid = req.getParameter("tid");
        String tname = req.getParameter("tname");
        String tsex = req.getParameter("tsex");
        String tphone = req.getParameter("tphone");
        String temail = req.getParameter("temail");
        String cid = req.getParameter("cid");
        String pn = req.getParameter("pn");

        Teacher teacher = new Teacher(Integer.valueOf(tid), tname, tsex, tphone, temail, Integer.valueOf(cid));

        int i = teacherService.updateById(teacher);
        if (i > 0) {
            this.main(req, resp, pn);
        }
    }

    /**
     * 查询所有教师数量
     */
    protected void count(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");

        long count = teacherService.count();
        PrintWriter writer = resp.getWriter();
        writer.println(count);
        writer.flush();
    }

    /**
     * 根据教师名查询教师信息
     */

    protected void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String tname = req.getParameter("tname");

        String pageNo = req.getParameter("pageNo");
        if (pageNo == null || Integer.parseInt(pageNo) <= 0) {
            pageNo = "1";
        }

        Page<Teacher> page = teacherService.query(tname, Integer.valueOf(pageNo));

        List<Teacher> teacherList = page.getList();
        List<TeacherRespVo> respVos = teacherList.stream().map(teacher -> {
            try {
                TeacherRespVo respVo = new TeacherRespVo();
                BeanUtils.copyProperties(respVo, teacher);
                String cname = collegeService.getById(teacher.getCid()).getCname();
                respVo.setCname(cname);

                return respVo;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());

        Page<TeacherRespVo> voPage = new Page<>();
        try {
            //属性对拷
            BeanUtils.copyProperties(voPage, page);
            voPage.setList(respVos);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        req.setAttribute("tname", tname);
        req.setAttribute("page", voPage);
        req.getRequestDispatcher("/teacher_manage.jsp").forward(req, resp);
    }
}
